package com.lw.interceptor;

import com.lw.exception.CommonException;
import com.lw.utils.JwtUtils;
import com.lw.utils.ResultCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
public class JwtInterceptor implements HandlerInterceptor {
//    @Autowired
    JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token 解析token获取claims存入request域
        if (!StringUtils.isEmpty( request.getHeader( "Authorization" ) ) && request.getHeader( "Authorization" ).startsWith( "Bearer " )) {
            //获取token
            String token = request.getHeader( "Authorization" ).replace( "Bearer ", "" );
            //解析token
            Claims claims = jwtUtils.parseJwt( token );
            if (claims != null) { //不完善 只测试一个
               // 获取当前用户可访问的用户api权限
                String apis = (String) claims.get( "apis" );
                //通过handler
                HandlerMethod h=(HandlerMethod) handler;
                GetMapping annotation = h.getMethodAnnotation( GetMapping.class );
                String name = annotation.name();
                if (apis.contains( name )){
                    request.setAttribute( "claims", claims );
                    return true;
                }else {
                    throw new CommonException( ResultCode.UNAUTHORISE );
                }
            }
        }
            throw new CommonException( ResultCode.UNAUTHENTICATED );
    }

}
